package old;

import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.net.URI;
import java.text.DecimalFormat;

import javax.swing.AbstractAction;

import org.openstreetmap.osm.data.coordinates.EastNorth;
import org.openstreetmap.osm.data.coordinates.LatLon;


public class ShowURL extends AbstractAction {

	private static final DecimalFormat DF = new DecimalFormat("#.########");
	
	private final CoordinateHelper coordinateHelper;

	private final boolean google;

	public ShowURL(CoordinateHelper coordinateHelper, boolean google) {
		super(google ? "Show in Google Maps" : "Show in Open Streat Map");
		this.coordinateHelper = coordinateHelper;
		this.google = google;
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		String url = null;
		if (google) {
			url = toGoogleURL(coordinateHelper);
		} else {
			url = toOSMURL(coordinateHelper);
		}
		System.out.println(url);
		showURL(url);
	}

	private static String toOSMURL(CoordinateHelper ch) {
		StringBuffer sb = new StringBuffer();
        sb.append("http://www.openstreetmap.org/?");
        LatLon c = ch.getProjection().eastNorth2latlon(ch.getCenter());
        sb.append("lat=" + DF.format(c.lat()) + "&lon" + DF.format(c.lon()));
		sb.append("&zoom=14&layers=M");
        return sb.toString();
	}

	private static String toGoogleURL(CoordinateHelper ch) {
        StringBuffer sb = new StringBuffer();
        sb.append("http://maps.google.com/?");
        LatLon c = ch.getProjection().eastNorth2latlon(ch.getCenter());
        sb.append("ll=" + DF.format(c.lat()) + "," + DF.format(c.lon()));
        EastNorth max = ch.getProjection().latlon2eastNorth(ch.getBounds().getMax());
        EastNorth min = ch.getProjection().latlon2eastNorth(ch.getBounds().getMin());
        double latDiff = 180.0 / (2 * Math.PI) * (max.east() - min.east());
        double longDiff = 180.0 / (2 * Math.PI) * (max.north() - min.north());
        sb.append("&spn=" + DF.format(latDiff) + "," + DF.format(longDiff));
        return sb.toString();
	}

	private void showURL(String googleURL) {
		Desktop desktop = null;
	    if (Desktop.isDesktopSupported()) {
	        desktop = Desktop.getDesktop();
	        try {
		        URI uri = new URI(googleURL);
				desktop.browse(uri);
	        } catch (Exception ex) {
	        	ex.printStackTrace();
	        }
	    }
	}
	
}